<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="isUpdate ? t('common.edit') : t('common.create')"
      @register="register"
      @ok="handleSubmit"
      @cancel="handleClose"
      :destroyOnClose="true"
      :minHeight="400"
      :width="600"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getClassPropForm } from './data';
  import { addDocType, updateDocType } from '/@/api/demo/system';

  const { t } = useI18n();
  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();
  const isUpdate = ref(false);
  const docTypeId = ref('');
  const newIndex = ref(null);
  const canChange = ref('');
  const tableData = ref([]);

  // 定义弹窗是否可见
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    docTypeId.value = data.docTypeId;
    newIndex.value = data.newIndex;
    tableData.value = data.tableData;
    setFieldsValue({ dispIndex: newIndex.value });
    if (unref(isUpdate)) {
      // 更新
      canChange.value = data.record.canChange;
      const newData = data.record;
      const attrMap = {
        '264': { readOnly: true, newAttr: '256' },
        '256': { readOnly: false },
        '136': { readOnly: true, newAttr: '128' },
        '128': { readOnly: false },
        '8456': { readOnly: true, newAttr: '8448' },
        '8448': { readOnly: false },
        '1032': { readOnly: true, newAttr: '1024' },
        '1024': { readOnly: false },
        '776': { readOnly: true, newAttr: '768' },
        '768': { readOnly: false },
      };

      // 检查是否存在对应的 attr
      if (attrMap.hasOwnProperty(newData.attr)) {
        // 获取对应的映射
        const mapping = attrMap[newData.attr];

        // 更新 readOnly 属性
        newData.readOnly = mapping.readOnly;

        // 如果有新的 attr 值，则更新 attr
        if (mapping.newAttr) {
          newData.attr = mapping.newAttr;
        }
      }
      newData.isOnly = newData.isOnly === '1' || newData.isOnly === true;
      newData.pdmnull = newData.pdmnull === '1' || newData.pdmnull === true;
      setFieldsValue(newData);
    }
  });

  const [registerForm, { validate, setFieldsValue }] = useForm({
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
    schemas: getClassPropForm(isUpdate, canChange),
    showActionButtonGroup: false,
  });

  async function handleSubmit() {
    const values = await validate();
    let isHaveSensitivity = tableData.value.some((item) => item.isOnly === '1');
    if (isHaveSensitivity || !!values.isOnly) {
      const attrMap = {
        '256': '264',
        '128': '136',
        '8448': '8456',
        '1024': '1032',
        '768': '776',
      };

      if (values.readOnly && attrMap.hasOwnProperty(values.attr)) {
        values.attr = attrMap[values.attr];
      }
      Reflect.deleteProperty(values, 'readOnly');
      values.isOnly = values.isOnly ? '1' : '0';
      values.pdmnull = values.pdmnull ? '1' : '0';
      if (unref(isUpdate)) {
        // 修改
        try {
          setModalProps({ confirmLoading: true });
          values.docTypeId = docTypeId.value;
          values.canChange = canChange.value;
          await updateDocType(values);
          closeModal();
          emit('success');
          createMessage.success(t('common.saveSuccess'));
        } finally {
          setModalProps({ confirmLoading: false });
        }
      } else {
        // 新增
        try {
          setModalProps({ confirmLoading: true });
          values.docTypeId = docTypeId.value;
          values.canChange = '1';
          await addDocType(values);
          closeModal();
          emit('success');
          createMessage.success(t('common.saveSuccess'));
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
    } else {
      createMessage.warning(t('routes.demo.partSetting.sensitivePropertyAtLeastOne'));
    }
  }

  // 关闭弹窗
  const handleClose = () => {
    canChange.value = '';
    tableData.value = [];
    closeModal();
  };
</script>

<style lang="less" scoped></style>
